import { createRouter, createWebHashHistory, RouteRecordRaw } from 'vue-router'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'

NProgress.configure({
  showSpinner: false
})

const Header = () => import('@/components/Header.vue')
const Footer = () => import('@/components/Footer.vue')
const Home = () => import('@/views/Home.vue')
const Category = () => import('@/views/Category.vue')
const Show = () => import('@/views/Show.vue')
const Contact = () => import('@/views/Contact.vue')

const Icons = () => import('@/views/Icons.vue')
const Users = () => import('@/views/user/Users.vue')
const UserStart = () => import('@/views/user/UserStart.vue')
const UserDetail = () => import('@/views/user/UserDetail.vue')
const UserEdit = () => import('@/views/user/UserEdit.vue')
const NotFound = () => import('@/views/notFound/index.vue')

const routes: RouteRecordRaw[] = [
  {
    path: '/',
    components: {
      default: Home,
      'router-view-footer': Footer,
    },
    meta: {
      title: '首页'
    },

  },
  {
    path: '/category/:id',
    components: {
      default: Category,
      'router-view-footer': Footer,
    },
    meta: {
      title: '分类'
    }
  },
  {
    path: '/show/:id',
    components: {
      default: Show,
      'router-view-footer': Footer,
    },
    meta: {
      title: '展示'
    }
  },
  {
    path: '/contact',
    components: {
      default: Contact,
    },
    meta: {
      title: '联系'
    }
  },
  {
    path: '/users',
    component: Users,
    children: [
      {
        path: '',
        component: UserStart,
      },
      {
        name: 'userDetail',
        path: ':id',
        component: UserDetail,
        props: true,
      },
      {
        name: 'userEdit',
        path: ':id/edit',
        component: UserEdit,
        props: (route: any) => ({
          id: route.params.id,
          name: route.query.name,
          age: 18,
          level: '五级'
        }),
        // 独享守卫，只有在进入该路由时才会执行，确保通过点击“编辑用户”按钮进入该路由，在地址栏输入或者粘贴地址无效
        //非常有用
        beforeEnter: (to: any, from: any, next: any) => {
          if (from.name !== 'userDetail') {
            next('/')
          } else {
            next()
          }
        }
      },
    ],
    meta: {
      title: '用户管理',
    }
  },
  {
    path: '/:notFound(.*)',
    component: NotFound,
    name: 'notFound',
  }
]

const router = createRouter({
  history: createWebHashHistory(),
  routes,
  linkActiveClass: 'active',
  // 滚动行为,当切换路由时,滚动到顶部，当点击浏览器返回按钮时，滚动到上次的位置
  scrollBehavior(to, from, savedPosition) {
    if (savedPosition) {
      return savedPosition
    } else {
      return { top: 0 }
    }
  }
})

// 路由守卫
// 全局前置守卫
router.beforeEach((to, from, next) => {
  NProgress.start()

  if (to.meta?.title) {
    document.title = to.meta.title as string
  }
  next()
})
// 全局后置守卫
router.afterEach((to, from) => {
  NProgress.done()
})

export default router